<template>
  <!-- 表单栏 -->
  <div class="table">
    <BaseTable
      v-loading="tableLoading"
      :columns="columns"
      :data="dataList"
      @handleCurrentChange="handleCurrentChange"
      @handleAction="handleAction"
      :default-expand-all="expandAll"
      row-key="code" :tree-props="{ children: 'children', label: 'name' }"
      lazy
      :load="load"
      highlight-current-row
    >
      <template v-slot:action>
        <el-button type="primary" @click="handleCreate">新增一级</el-button>
      </template>
    </BaseTable>

    <!-- 弹窗 -->
    <el-dialog
      :title="action == 'add' ? '新增' : '编辑'"
      v-model="showModal"
      :before-close="handleClose"
    >
      <el-form
        ref="dialogForm"
        :rules="rules"
        :model="dataForm"
        label-width="100px"
      >
        <el-form-item label="地址编号" prop="code">
          <el-input
            v-model="dataForm.code"
            placeholder="请输入地址编号"
          />
        </el-form-item>
        <el-form-item label="地址名称" prop="name">
          <el-input
            v-model="dataForm.name"
            placeholder="请输入地址名称"
          />
        </el-form-item>
        <el-form-item label="父级地址编号" prop="pcode">
          <el-input
            disabled
            v-model="dataForm.pcode"
            placeholder="请输入父级地址编号"
          />
        </el-form-item>
        <el-form-item label="地址级别" prop="level">
          <el-input
            v-model="dataForm.level"
            placeholder="请输入地址级别"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import {
  queryAddressList,
  addressAdd,
  addressEdit,
  addressDel,
} from "@/api/address";
import { ElMessage } from "element-plus";
/****************************************** data ******************************************/

const load = async (
  row: DataModel,
  treeNode: unknown,
  resolve: (date: DataModel[]) => void
) => {
  let data: DataModel[] = (await queryAddressList({pcode:row.code})).data;
  return resolve(data)
}

// 展开所有
const expandAll = ref(false)

// 参数
const pager = reactive({
  page: 1,
  limit: 10,
  total: 0,
});
// 渲染数据
const dataList = ref(<DataModel[]>[]);

// 编辑动作：add,edit,delete
const action = ref("");

// 弹窗变量
const showModal = ref(false);

// 弹窗ref
const dialogForm = ref(<any>null);

// 表单loading
const tableLoading = ref(false);

// 表格提交数据
interface DataModel {
  id?: number, //主键ID
  code: string, //地址编号
  name: string, //地址名称
  pcode: string, //父级地址编号
  level: number, //地址级别
  children?: DataModel[],
  hasChildren?: boolean
}
const dataForm = ref(<DataModel>{});

// 定义动态表格的格式
const columns = reactive([
  {
    type: "index",
    label: "序号",
    width: "60"
  },
  {
    label: "地址编号",
    prop: "code",
  },
  {
    label: "地址名称",
    prop: "name",
  },
  // {
  //   label: "父级地址编号",
  //   prop: "pcode",
  // },
  {
    label: "地址级别",
    prop: "level",
  },
  {
    label: "创建时间",
    prop: "created_time",
  },
  {
    label: "更新时间",
    prop: "updated_time",
  },
 {
    type: "action",
    label: "操作",
    width: 250,
    list: [{ text: "添加下级地址", type: "text", cond: { prop: "level", value: [1,2] }}, { text: "编辑", type: "text" }, { text: "删除" }],
  },
]);

// 弹窗校验规则
const rules = reactive({
  id: [
    {
      required: true,
      message: "请输入主键ID",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入地址编号",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: true,
      message: "请输入地址名称",
      trigger: "blur",
    },
  ],
  pcode: [
    {
      required: true,
      message: "请输入父级地址编号",
      trigger: "blur",
    },
  ],
  level: [
    {
      required: true,
      message: "请输入地址级别",
      trigger: "blur",
    },
  ],
  created_time: [
    {
      required: true,
      message: "请输入创建时间",
      trigger: "blur",
    },
  ],
  updated_time: [
    {
      required: true,
      message: "请输入更新时间",
      trigger: "blur",
    },
  ],
});
/****************************************** 生命周期函数 ******************************************/
onMounted(() => {
  handleQuery();
});

/****************************************** method ******************************************/

// 查询
const handleQuery = async () => {
  tableLoading.value = true;
  let data: DataModel[] = (await queryAddressList({pcode:"0"})).data;
  dataList.value = data;
  tableLoading.value = false;
};

// 分页事件处理
const handleCurrentChange = (current: number) => {
  pager.page = current;
  handleQuery();
};

// 新增
const handleCreate = () => {
  action.value = "add";
  showModal.value = true;
};

// 操作
const handleAction = async ({ text, row }: any) => {
  if (text === "编辑") {
    action.value = "edit";
    showModal.value = true;
    await nextTick();
    Object.assign(dataForm.value, row);
  } else if (text === "删除") {
    await addressDel({ id: row.id });
    ElMessage({ message: "删除成功", type: "success" });
    handleQuery();
  }else if (text === "添加下级地址") {
    action.value = "add";
    dataForm.value.pcode = row.code;
    showModal.value = true;
  }
};

// 取消
const handleClose = () => {
  showModal.value = false;
  handleReset(dialogForm);
};

// 重置
const handleReset = (form: any) => {
  form.value.resetFields();
};

// 提交
const handleSubmit = () => {
  let res: any;
  dialogForm.value.validate(async (valid: boolean) => {
    if (valid) {
      let params = toRaw(dataForm.value);
      let model:DataModel = {
        code: params.code, //地址编号
        name: params.name, //地址名称
        pcode: params.pcode, //父级地址编号
        level: params.level, //地址级别
      }
      if (action.value === "add") {
        res = await addressAdd(params);
      } else if (action.value === "edit") {
        model.id = params.id
        res = await addressEdit(params);
      }
      if (res && res.code === 200) {
        showModal.value = false;
        ElMessage({ message: "操作成功", type: "success" });
        handleReset(dialogForm);
        handleQuery();
      }
    }
  });
};
</script>

<style lang="scss" scoped></style>
